<template>
  <base-breadcrumb
    :title="title"
    :breadcrumb="!isAudit"
  >
    <!-- 质量策划方案管理编辑 -->
    <a-form-model
      ref="ruleForm"
      :model="form"
      :label-col="{ span: 6 }"
      :wrapper-col="{ span: 18 }"
      :rules="editModel != 0 ? rules : {}"
      id="base-breadcrumb"
      style="position: relative"
    >
      <a-spin :spinning="loading[0] || loading[1]">
        <!-- 基本信息 -->
        <a-card
          :bordered="false"
          style="margin-bottom: 80px"
        >
          <title-name title="基本信息"></title-name>
          <custom-form
            :formList="formList"
            :form="form"
            :editModel="editModel == 0 ? 'V' : ''"
            @selectOrg="selectOrg"
            ref="form"
          >
          </custom-form>
          <title-name title="附件" />
          <BTableUpload
            v-model="form.fileArrays"
            :disabled="editModel == 0"
            business-code="QM04"
          />
        </a-card>
      </a-spin>
      <!-- 页脚操作栏 -->
      <div class="btn_box page-btn-right-top">
        <!--<a-button-->
        <!--:disabled="loading[0] || loading[1]"-->
        <!--v-if="editModel == 1 && statusCode === '0' && form.version && form.version <= 1"-->
        <!--type="danger"-->
        <!--class="button_right"-->
        <!--@click="handleRemove"-->
        <!--&gt;删除草稿</a-button-->
        <!--&gt;-->
        <a-button
          :loading="loading[0]"
          :disabled="loading[1]"
          v-if="(editModel == 1 && (statusCode === '0' || statusCode === '3')) || editModel == 2"
          type="primary"
          class="button_right"
          @click="handleSubmit(0)"
        >{{ statusCode === '2' || statusCode === '3' || form.version > 1 ? '保存' : '保存草稿' }}</a-button>
        <a-button
          :loading="loading[1]"
          :disabled="loading[0]"
          v-if="
            (editModel == 1 && (statusCode === '0' || statusCode === '3')) ||
            editModel == 2 ||
            (editModel != 0 && statusCode === '2')
          "
          type="primary"
          class="button_right"
          @click="handleSubmit(1)"
        >提交</a-button>
        <a-button
          v-if="checkVisibleInDetail"
          type="primary"
          @click="handleActiveClose"
        >关闭</a-button>
      </div>
    </a-form-model>
    <selectApprover
      :businessId="businessId"
      :processConfig="setProcessConfig"
    ></selectApprover>
  </base-breadcrumb>
</template>

<script>
import { plotProgram } from '@/api/quality/quality' // api
import BaseEditPage from '@/views/baseEditPage' // 编辑详情页基础配置
// import BaseInfo from '@/components/businessComponents/BaseInfo' // 基础信息
import SelectSubCompany from '@/components/Select/SelectSubCompany' // 分公司
import SelectProject from '@/components/Select/SelectProject' // 项目名称
import SelectPersonByProject from '@/components/Select/SelectPersonByProject'
import BTableUpload from '@/components/BComponents/BTableUpload'
import Selector from '@/components/Select/Selector'

export default {
  name: 'a' + Date.now(),
  extends: new BaseEditPage(),
  components: {
    // BaseInfo,
    BTableUpload
  },
  props: {
    // 审批页
    isAudit: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      loading: { 0: false, 1: false }, // 草稿和提交按钮loding
      editModel: 0, // 操作状态:0 查看;1 编辑;2 新增
      id: '', // 业务id
      historyId: '', // 履历id
      form: {
        branchCompanyId: '',
        fillerDate: '',
        filler: '',
        branchPname: ''
      },
      statusCode: '', // 审批状态
      rules: {
        branchCompanyId: [{ required: true, message: '请选择分公司', trigger: 'change' }],
        projectId: [{ required: true, message: '请选择项目', trigger: 'change' }],
        plannerEmployeeId: [{ required: true, message: '请选择策划人', trigger: 'blur' }],
        planningDate: [{ required: true, message: '请选择策划时间', trigger: 'change' }],
        planType: [{ required: true, message: '请选择策划时间', trigger: 'blur' }],
        textPage: [{ required: true, message: '请填写正文页数(正整数)', trigger: 'blur' }],
        attachPage: [{ required: true, message: '请填写正文页数(正整数)', trigger: 'blur' }],
        describes: [{ required: true, message: '请填写版本描述', trigger: 'blur' }]
        // fileArrays: [{ type: 'array', required: true, message: '请上传文件', trigger: 'blur' }],
      },
      init: false,
      titles: ['质量策划查看', '质量策划编辑', '质量策划新增', '质量策划调整'],
      //获取流程配置值
      processConfig: null,
      //点击提交发送流程配置值
      setProcessConfig: null,
      businessId: null
    }
  },
  watch: {
    'form.fileArrays'(e) {
      if (this.editModel != 0 && this.init) {
        this.$nextTick(() => {
          this.$refs.ruleForm?.validateField('fileArrays')
        })
      }
    }
  },
  async mounted() {
    // 不为添加时请求详情
    if (this.editModel != 2) {
      this.loading[0] = true
      let args = {}
      if (this.businessId) {
        args.businessId = this.businessId
      } else {
        args.id = this.id
      }
      this.historyId && (args.historyId = this.historyId)
      plotProgram
        .getDetail(args)
        .then((res) => {
          this.loading[0] = false
          this.form = res.data
          this.statusCode = res.data.statusCode // 审批状态
          this.form.planTypeName = res.data.planType.name
          this.form.branchPname = this.form.branchCompanyName + '/' + this.form.projectName
          this.form.planType = {
            key: res.data.planType.id,
            value: res.data.planType.name
          }
          this.$nextTick(() => {
            this.init = true
          })
        })
        .catch((res) => {
          this.loading[0] = false
        })
    } else {
      this.form.filler = JSON.parse(sessionStorage.getItem('ycloud-user_info'))?.name // 默认填报人
      this.form.fillerDate = this.$dateFormat(new Date(), 'D') // 默认填报时间
      this.$nextTick(() => {
        this.init = true
      })
    }
    //获取通过获取流程配置值
    this.processConfig = await this.$getConfigFn('quality_planning_plan')
  },
  computed: {
    // 表单列表
    formList() {
      return [
        {
          type: 'orgTree',
          keyName: 'projectId',
          label: '所属单位',
          isNeedAuth: true,
          isAutoSelectFirst: this.editModel == 2,
          notIsAutoSelectFirst:this.editModel == 2,
          span: this.editModel == 0 ? 8 : 16,
          isNoBorder: this.editModel == 0,
          viewName: 'branchPname',
          checkStrictly: true
        },
        // {
        //   type: SelectSubCompany,
        //   keyName: 'branchCompanyId',
        //   label: '所属分公司',
        //   viewName: 'branchCompanyName',
        //   attrs: {
        //     autoSelected: this.editModel == 2
        //   }
        // },
        // {
        //   type: SelectProject,
        //   keyName: 'projectId',
        //   label: '所属项目',
        //   viewName: 'projectName',
        //   attrs: {
        //     keyValue: 'branchCompanyId',
        //     autoSelected: this.editModel == 2,
        //     isClear: this.editModel == 2,
        //     form: this.form
        //   }
        // },
        {
          type: SelectPersonByProject,
          keyName: 'plannerEmployeeId',
          viewName: 'planner',
          label: '策划人',
          attrs: {
            projectId: this.form.projectId,
            showSearch: true
          }
        },
        {
          keyName: 'planningDate',
          type: 'a-date-picker',
          placeholder: '请选择日期',
          label: '策划时间',
          attrs: {
            valueFormat: 'YYYY-MM-DD'
          }
        },
        {
          keyName: 'filler',
          type: 'a-input',
          disabled: true,
          label: '填报人'
        },
        {
          keyName: 'fillerDate',
          type: 'a-date-picker',
          disabled: true,
          label: '填报时间',
          attrs: {
            valueFormat: 'YYYY-MM-DD'
          }
        },
        {
          type: Selector,
          keyName: 'planType',
          label: '方案类别',
          viewName: 'planTypeName',
          attrs: {
            selectType: '41',
            labelInValue: true
          }
        },
        {
          keyName: 'textPage',
          type: 'BaseInputNumber',
          label: '正文页数',
          attrs: {
            min: 0,
            formatter: (value) => {
              return !isNaN(value) ? String(value).replace(/\./g, '') : 0
            }
          }
        },
        {
          keyName: 'attachPage',
          type: 'BaseInputNumber',
          label: '附页页数',
          attrs: {
            min: 0,
            formatter: (value) => {
              return !isNaN(value) ? String(value).replace(/\./g, '') : 0
            }
          }
        },
        {
          keyName: 'describes',
          label: '版本描述',
          type: 'BaseTextarea',
          autoSize: { minRows: 10, maxRows: 10 },
          attrs: {
            maxLength: 3000
          },
          ellipsis: true,
          span: 24
        }
        // {
        //   slot: true,
        //   keyName: 'fileArrays',
        //   label: '附件上传',
        //   span: 24,
        // },
      ]
    }
  },
  methods: {
    selectOrg(val) {
      this.form.branchCompanyId = val[val.length - 2].orgId
      console.log(this.$refs, '2')
      // this.$refs.form.clearValidate('projectId')
      this.$set(this.form, 'plannerEmployeeId', '')
    },
    /**
     * 项目改变时
     */
    handleChange(name) {
      if (name === 'projectId') {
        let form = this.form
        if (form.plannerEmployeeId) {
          form.plannerEmployeeId = ''
        } else {
          this.$set(this.form, 'plannerEmployeeId', '')
        }
      }
    },
    /**
     * 删除草稿
     */
    handleRemove() {
      this.$confirm({
        title: '温馨提示',
        content: '确定删除草稿？',
        onOk: () => {
          return plotProgram.remove({ id: this.id }).then((res) => {
            this.$message.success('删除成功！')
            // 关闭当前页
            this.$multiTab.close()
          })
          // .catch((res) => {
          //   this.$message.warning('删除失败！')
          // })
        }
      })
    },
    /**
     * 提交表单
     */
    handleSubmit(statusCode) {
      try {
        console.log(this.form.planTypeId)
        // return false
        let that = this
        that.setProcessConfig = null
        let name = ['update', 'create', 'adjustment'][that.editModel - 1] // 根据操作切换url地址
        // 校验表单
        if (statusCode == 1 && this.form.fileArrays.length == 0) {
          this.$message.error('请上传附件')
          return
        }
        that.$refs.ruleForm.validate((e) => {
          if (e || statusCode === 0) {
            statusCode === 0 && that.$refs.ruleForm.clearValidate()
            // 提交表单
            that.loading[statusCode] = true
            let form = that.$clone(that.form)
            form.statusCode = that.statusCode == '3' && statusCode == 0 ? that.statusCode : statusCode
            form.planTypeId = that.form?.planType?.key
            this.submitApprovalConfirm(this.processConfig, (flag) => {
              if(!flag) {
                that.loading[statusCode] = false
                return
              }
              plotProgram[name](form)
                .then((res) => {
                  that.loading[statusCode] = false
                  that.$message.success(['保存', '提交'][statusCode] + '成功！')
                  if (statusCode * 1 === 1) {
                    //提交时，返回id
                    that.businessId = res.data.businessId
                    that.setProcessConfig = this.processConfig
                    return
                  } else {
                    that.$multiTab.close()
                  }
                })
                .catch((res) => {
                  // that.$message.warning(['保存', '提交'][statusCode] + '失败！')
                  that.loading[statusCode] = false
                })
            })
          } else {
            this.$message.warning('请填写完所有必填项信息')
          }
        })
      } catch (error) {
        console.log(error)
      }
    }
  }
}
</script>
